
// Set vars
var no_comment_ar = ["7","8","9","10","11","14","15","16","17","18","19","23","24","29","30","39","40","41","42","43","44"];
var hightlight_ar = [];
var feed_ar = new Array();
var submits = new Array();
var saving = false;
var feed_max_posts = 15;
var feed_show = feed_show || "personal";
var feed_nat = feed_nat || "en";
var feed_div = feed_div || 1;
var feed_gro = feed_gro || 1;
var feed_session = feed_session || 1;

if (feed_language == undefined) {
	var feed_language = {
		"league":global_content["league"], //"League",
		"match":global_content["match"], //"Match",
		"comment":global_content["comment"], //"Comment",
		"reveal":global_content["reveal"], //"Reveal",
		"comments":global_content["comments"], //"Comments",
		"personal":global_content["personal"], //"Personal",
		"buddy":global_content["buddies"], //"Buddies",
		"read":global_content["read"], //"Read",
		"upcoming":global_content["upcoming"], //"Upcoming"

		"write":global_content["feed_431"], //"Write Comment...",
		"view_more":global_content["feed_432"], //"View more...",
		"more":global_content["feed_433"], //"More..",
		"pa":global_content["feed_434"] //"PA",
	};
}

function hideElement(elem) {
	$(elem).hide();
}

function showElement(elem) {
	$(elem).slideDown(200);
}
function make_element(type, classname, inner) {
	var element = document.createElement(type);
	if (classname) element.className = classname;
	if (inner) element.innerHTML = inner;
	return element;
}
function make_image(src, href, id, class_name) {
	var i = document.createElement("img");
	if (id) i.id = id;
	if (class_name) i.className = class_name;
	i.src = src;
	if (href) {
		var a = document.createElement("a");
		a.href = href;
		a.appendChild(i);
		return a;
	}
	return i;
}
function timeLeft(secs) {
	if (secs <= 0) {
		return "Expired";
	}
	var ret = "";
	var tmp_d = tmp_h = tmp_m = tmp_s = 0;
	if (secs > 86400) {
		tmp_d = Math.floor(secs/86400);
		tmp_h = Math.floor((secs-(tmp_d*86400))/3600);
		ret = tmp_d+global_content["days_abbr"]+"&nbsp;"+tmp_h+global_content["hours_abbr"];
	} else if (secs > 3600) {
		tmp_h = Math.floor(secs/3600);
		tmp_m = Math.floor((secs-tmp_h*3600)/60);
		ret = tmp_h+global_content["hours_abbr"]+"&nbsp;"+tmp_m+global_content["minutes_abbr"];
	} else if (secs > 120) {
		tmp_m = Math.floor(secs/60);
		tmp_s = secs-(tmp_m*60);
		ret = tmp_m+global_content["minutes_abbr"]+"&nbsp;"+tmp_s+global_content["seconds_abbr"];
	} else {
		ret = "<&nbsp;2"+global_content["minutes_abbr"];
	}
	return ret;
}
function make_tab_a(lang) {
	var a = make_element("a", null, feed_language[lang]);
	a.href = "#feed-"+lang;
	//a.setAttribute("onclick", "send_and_load('"+lang+"')");
	return a;
}

function make_feed(max_feed_entries) {
	//alert(dump(feed_ar));

	feed_max_posts = max_feed_entries || feed_max_posts;

	var ul = make_element("ul", "feed");
	ul.cellSpacing = "0";

	var count = 0;

//	var li = make_element("li", "tabs");

//	li.appendChild(make_tab_a("personal"));
//	li.appendChild(make_tab_a("buddy"));
//	li.appendChild(make_tab_a("league"));
//	li.appendChild(make_tab_a("pa"));
//	li.appendChild(make_tab_a("comments"));
//	li.appendChild(make_image("http://static.trophymanager.com/pics/five_horizontal_loading.gif", null, "img_loading", "loading"));

//	ul.appendChild(li);

	var sort_arr = new Array();
	var sortable = new Array();
	var sortable_float = new Array();

	for (var i in feed_ar) {
		var tmp = new Array();
		if (feed_ar[i]["upcoming"]) {
			tmp["id"] = i;
			tmp["sort"] = parseInt(feed_ar[i]["sort"] || 0);
			sortable_float.push(tmp);
		} else {
			tmp["id"] = i;
			tmp["sort"] = parseInt(feed_ar[i]["sort"] || 0);
			sortable.push(tmp);
		}
	}

	sortable.sort(
		function(a,b){
			return a["sort"] - b["sort"];
		}
	);
	sortable_float.sort(
		function(a,b){
			return a["sort"] - b["sort"];
		}
	);

	var last_upcoming = sortable_float.length-1;

	sortable = sortable_float.concat(sortable);

	for (var i in sortable) {
		feed_entry = feed_ar[sortable[i]["id"]];
		i = sortable[i]["id"];
		if (count >= feed_max_posts) break;

		var li = document.createElement("li");
		if (feed_entry["upcoming"]) {
			li.className = "orange";
		}
		if (i == last_upcoming) {
			li.style.marginBottom = "1px";
		}

		if(feed_entry["upcoming"]) {
			var inner_event_text_box = make_element("div", "icon_box", feed_language["upcoming"]+": "+feed_entry["inner"]);
		} else {
			if (feed_entry["type"] == 29 || feed_entry["type"] == 30) {
				var tmp = "<span style='color:#cf0; cursor:pointer;' onclick='this.innerHTML=\""+feed_entry["replace"]+"\";this.style.color=\"#fff\";this.style.cursor=\"auto\" '>"+feed_language["reveal"]+"</span>";
				var inner_event_text_box = make_element("div", "icon_box", feed_entry["inner"]+" "+tmp+" <span>&bull;&nbsp;"+timeLeft(Math.max(0,feed_entry["time"]))+"</span>");
			} else {
				var inner_event_text_box = make_element("div", "icon_box", feed_entry["inner"]+" <span>&bull;&nbsp;"+timeLeft(Math.max(0,feed_entry["time"]))+"</span>");
			}
		}
		/*if (feed_entry["match_id"]) {
			inner_event_text_box.innerHTML += " &bull;&nbsp;<a href='live_prematch.php?matchid="+feed_entry["match_id"]+"'>View</a>";
		}*/

		inner_event_text_box.style.backgroundImage = "url('http://static.trophymanager.com/pics/feed/feed_icons/"+feed_entry["type"]+".gif')";
		if(feed_entry["unread"])
		{
			$(inner_event_text_box).prepend("<img src='http://static.trophymanager.com/pics/eight_star_icon.png' />");
		}
		var icon_div = document.createElement("div");
		if (feed_entry["type"] == 11) {
			// PA
			var topic_box = make_element("div", "add_comment", "<a href='"+feed_entry["topic_url"]+"'>"+feed_language["read"]+"</a>");
			icon_div.appendChild(topic_box);
		} else if (array_search(feed_entry["type"], no_comment_ar) < 0 && !feed_entry["comments"]) {
			var start_comment_box = make_element("div", "add_comment", feed_language["comment"]);
			start_comment_box.id = i;
			start_comment_box.onclick = function() {
				open_comment(this["id"]);
			}
			icon_div.appendChild(start_comment_box);
		}

		icon_div.appendChild(inner_event_text_box);
		li.appendChild(icon_div);

		comments = make_element("div", "comment_text");

		comments_inner = document.createElement("div");

		// Comment text box
		comments.appendChild(comments_inner);
		li.appendChild(comments);


		// Add comment input box
		inner = document.createElement("div");
		inner.style.padding = 0;

		// - Input field
		// - - static
		var write_placeholder = make_element("div", null, feed_language["write"]);
		write_placeholder.i = i;
		write_placeholder.onclick = function() {
			open_comment(this["i"]);
		}

		// - - input
		var write_comment_input = document.createElement("input");
		write_comment_input.type = "text";
		write_comment_input.i = i;
		write_comment_input.maxChars = 250;
		$(write_comment_input).addClass("emboss");
		write_comment_input.onkeydown = function() {
			count_chars(this.i);
		}
		write_comment_input.onkeyup = function() {
			count_chars(this.i);
		}
		write_comment_input.setAttribute("onkeypress", "try_submit(event, "+i+")");
		hideElement(write_comment_input);

		add_comments = make_element("div", "comment_text");
		add_comments.style.marginTop = "1px";
//		$(add_comments).hide();
		if (!feed_entry["comments"]) {
			hideElement(add_comments);
		}

		add_comments.appendChild(inner);
		inner.appendChild(write_placeholder);
		inner.appendChild(write_comment_input);
		li.appendChild(add_comments);

		// Add write reply input + char count + hide it
		submit_box = document.createElement("div");
		submit_box.style.textAlign = "right";
		submit_box.style.margin = "1px 20px";
		hideElement(submit_box);

		char_count = make_element("span", "char_count", "250");

		submit_btn = make_element("div", "button", "<span class='button_border'>"+feed_language["comment"]+"</span>");
		submit_btn.i = i;
		submit_btn.onclick = function() {
			send_and_load("comment", this.i);
		}

		submits[i] = {"comments_inner": comments_inner, "comments":comments, "container":add_comments, "input":write_comment_input, "box":submit_box, "count":char_count, "placeholder":write_placeholder, "btn":submit_btn};

		fill_comments(i);

		submit_box.appendChild(char_count);
		submit_box.appendChild(submit_btn);
		li.appendChild(submit_box);

		ul.appendChild(li);
		count++;
	}

	if (max_feed_entries == 15) {
		var li = make_element("li", "view_more", "<span>"+feed_language["view_more"]+"</span>");
		li.onclick = function() {
			make_feed(100);
		}
		ul.appendChild(li);
	}

	$("#feed_div").html("");
	$("#feed_div").append(ul);
}

function fill_comments(id, mode) {
	// Comment text box
	// Full comments or semi (the first five comments only)
	mode = mode || "semi";
	if (feed_ar[id]["comments"]) {

		if (array_search(feed_ar[id]["type"], hightlight_ar) >= 0) {
			submits[id]["comments_inner"].innerHTML = "<img style='margin-left:-16px;position:absolute;' src='http://static.trophymanager.com/pics/feed/feed_comment_bob_blue.gif' />";
		} else {
			submits[id]["comments_inner"].innerHTML = "<img style='margin-left:-16px;position:absolute;' src='http://static.trophymanager.com/pics/feed/feed_comment_bob.gif' />";
		}

		var html = new String();
		var tmp_feed = new Array();
		if (mode == "semi") {
			if (feed_ar[id]["comments"].length > 5) {
				var more = make_element("span", "more", feed_language["more"]);
				more.setAttribute("onclick", "fill_comments("+id+", 'full')");
				submits[id]["comments_inner"].appendChild(more);
			}
			tmp_feed = feed_ar[id]["comments"].slice(-5);
		} else {
			tmp_feed = feed_ar[id]["comments"];
		}

		for (var m in tmp_feed) {
			if(tmp_feed.hasOwnProperty(m)){
				var v = tmp_feed[m];
				html += "<a href='/club/"+v["id"]+"'>"+v["name"].split(" ").join("&nbsp;")+"</a>:&nbsp;"+v["text"]+"<br />";
			}
		}
		submits[id]["comments_inner"].innerHTML += html;
		showElement(submits[id]["comments"]);
	} else {
		hideElement(submits[id]["comments"]);
	}
}

function try_submit(e, id) {
	var key = e.keyCode || e.which;
	if (key==13) send_and_load("comment", id);
}

function open_comment(id) {
	if (submits[id]) {
		showElement(submits[id]["box"]);
		showElement(submits[id]["container"]);
		showElement(submits[id]["input"]);
		hideElement(submits[id]["placeholder"]);
		submits[id]["input"].focus();
	}
}

function count_chars(id) {
	if (submits[id]) {
		if(submits[id]["input"].value.length > 250) submits[id]["input"].value = submits[id]["input"].value.substring(0, 250);
		submits[id]["count"].innerHTML = 250-submits[id]["input"].value.length;
	}
}

// Hash listener
var current_hash;
function set_hash(val)
{
	location.hash = "#"+val.toLowerCase();
}
function check_hash(default_feed) {
	default_feed = default_feed || "personal";
	var user_hash = "#"+default_feed;
	if (location.hash != current_hash) {
		current_hash = location.hash;
		if(location.hash == "#buddy" || location.hash == "#league" || location.hash == "#pa" || location.hash == "#comments"){
			user_hash = location.hash;
		}
		else{
			user_hash = "#"+default_feed;
		}
//			current_hash = location.hash;
		tmp_send = (user_hash == "") ? default_feed : user_hash.substr(1);
		$("#feed_tabs").children().removeClass("active_tab");
		$("#tab-"+tmp_send).addClass("active_tab");
		send_and_load(tmp_send);
	}
}

// JSON and start make_feed
function send_and_load(mode, id) {
	if (saving) {
		return false;
	} else {
		saving = true;

		if (mode != "comment") {
			var loading_img = $('<div class="align_center"/>');
			loading_img.html(make_image("http://static.trophymanager.com/pics/five_horizontal_loading.gif", null, "img_loading", "loading"));
			$("#feed_div").html(loading_img);
//			if($("#img_loading").length > 0) $("#img_loading").css("visibility","visible");
			// Call JSON

//			var params = "mode="+mode;
//			params += "&nat="+feed_nat+"&div="+feed_div+"&gro="+feed_gro+"&session="+feed_session;
			//alert(params);


			// On loaded info
			$.post("/ajax/club_feed.ajax.php", {"mode":mode,"country":feed_nat,"division":feed_div,"group":feed_gro,"session":feed_session}, function (data) {

					saving = false;
					if (data == null) {
						js_error("Error getting data");
					} else {
						new_comments_ar = data;
						if (new_comments_ar["error"]) {
							if (new_comments_ar["error"] == "no session") {
								//NO SESSION!
							} else {
								//SOME OTHER ERROR!
								alert("Error:"+new_comments_ar["error"]);
							}
						} else {
							feed_ar = new_comments_ar;
//							$("#feed_div").html("");
							make_feed(feed_max_posts);
						}
					}
			},"json");
		} else {
			submits[id]["btn"].innerHTML = "<img src='http://static.trophymanager.com/pics/five_horizontal_loading.gif' />";
			var text = submits[id]["input"].value;
			$.post("/ajax/club_feed.ajax.php",{"id":id,"text":text},function(data){
				saving = false;
				submits[id]["btn"].innerHTML = feed_language["comment"];
				if (data == null) {
					// ERROR
				} else {
					new_comments_ar = data;
					if (new_comments_ar["error"]) {
						if (new_comments_ar["error"] == "no session") {
							//NO SESSION!
						} else {
							//SOME OTHER ERROR!
						}
					} else {
						submits[id]["input"].value = "";
						count_chars(id);
						feed_ar[id]["comments"] = new_comments_ar;
						fill_comments(id, "full");
					}
				}
			},"json");
		}
	}
}
